import React, { useEffect, useState } from "react";
// 引入antd的样式
import {
  Button,
  Form,
  Input,
  Select,
  Table,
  Card,
  Col,
  Row,
  message,
} from "antd";
// 引入配置
import { useNavigate } from "react-router-dom";
import {
  PagingListRequest,
  hospitalListContentType,
  hospitalListRequest,
  hospitalDateType,
  regionReturnResultType,
} from "@/api/hospital/model/hospitalListTypes";
// 引入api请求
import {
  SendHospitalListRequest,
  ProvinceTypeRequest,
  cityTypeRequest,
  OnlineStatusRequest,
} from "@/api/hospital/hospitalList";
export default function HospitalList() {
  const navigate = useNavigate();
  //通过Form组件上的一个useForm方法,可以创建实例,然后在某一个Form组件上添加一个form属性,值为当前实例,那么Form表单和当前的form实例就关联起来了
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);
  // 控制当前页码的状态
  const [page, setPage] = useState(1);
  // 控制总数据的数量
  const [total, setTotal] = useState(0);
  // 控制当前每条显示的条数
  const [limit, setLimit] = useState(3);
  //控制查询时用户输入的表单参数
  const [paramsList, setParamsList] = useState<PagingListRequest>({});
  // 控制渲染表单渲染的数据
  const [tableData, setTableDate] = useState<hospitalListContentType>([]);
  // 省份的信息存储
  const [province, setProvince] = useState<regionReturnResultType>([]);
  // 市级区域的信息存储
  const [cityList, setCityList] = useState<regionReturnResultType>([]);
  // 区级数据的存储
  const [area, setArea] = useState<regionReturnResultType>([]);
  // 医院等级的数据
  const [hosGrade, setHosGrade] = useState<regionReturnResultType>([]);
  //控制重新渲染的state
  const [reRender, setReRender] = useState(true);
  useEffect(() => {
    setIsLoading(true);
    const CallFunction = async () => {
      const res = await SendHospitalListRequest(page, limit, paramsList);
      setTableDate(res.content);
      setTotal(res.totalElements);
      setIsLoading(false);
    };
    CallFunction();
  }, [page, limit, paramsList, reRender]);
  // 开始时获取省份数据
  useEffect(() => {
    const re = async () => {
      const res = await ProvinceTypeRequest();
      setProvince(res);
    };
    re();
  }, []);
  // 开始获取医院等级
  useEffect(() => {
    const res = async () => {
      const re = await cityTypeRequest("10000");
      setHosGrade(re);
    };
    res();
  }, []);
  // 回调函数
  // 1.当省份被点击时获取市级地区的数据
  const getCityList = async (value: string) => {
    const re = await cityTypeRequest(value);
    setCityList(re);
    form.setFieldsValue({ cityList: null, area: null });
    setArea([]);
  };
  // 2.当市级被点击时获取区级地区的数据
  const getAreaList = async (value: string) => {
    const re = await cityTypeRequest(value);
    setArea(re);
    form.setFieldsValue({ area: null });
  };
  // 3.点击上下线时 更改状态
  const StatusRequest = (id: string, status: number) => {
    return async () => {
      await OnlineStatusRequest(id, status);
      message.success(status ? "上线成功" : "下线成功");
      setReRender(!reRender);
    };
  };
  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render(logoData: string) {
        return <img width={120} src={`data:image/jpeg;base64,${logoData}`} />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: hospitalDateType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(_: any, data: hospitalDateType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(status: number) {
        return status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      render(_: any, data: hospitalDateType) {
        return (
          <div>
            <Button
              type="primary"
              onClick={() => {
                // 点击时通过params传参把id传过去
                navigate(`/syt/hospital/hospitalShow/${data.id}`);
              }}
            >
              查看
            </Button>
            {/* 点击时 将数据传输过去 */}
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitalSchedue/${data.hoscode}`);
              }}
            >
              排班
            </Button>
            {/* 点击上下线时 状态更改 */}
            <Button
              type="primary"
              onClick={StatusRequest(data.id, data.status ? 0 : 1)}
            >
              {data.status ? "下线" : "上线"}
            </Button>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        {/*  form={form} 使值一一对应可获取 通过setFieldsValue可以修改value显示的值 */}
        <Form
          name="basic"
          form={form}
          onFinish={(value: PagingListRequest) => {
            console.log(value);
            setParamsList(value);
            setPage(1);
          }}
        >
          <Row gutter={20}>
            <Col span={3}>
              <Form.Item name="province">
                <Select
                  placeholder="请选择省"
                  allowClear
                  onChange={getCityList}
                >
                  {province.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="cityList">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={getAreaList}
                >
                  {cityList.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="area">
                <Select placeholder="请选择区" allowClear>
                  {area.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hostype" style={{ width: 220 }}>
                <Select placeholder="医院类型" allowClear>
                  {hosGrade.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={3}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <Button type="default" htmlType="reset">
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={tableData}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange(current: number, pageSize: number) {
              setPage(current);
              setLimit(pageSize);
            },
          }}
        />
      </Card>
    </div>
  );
}
